package cn.stronglink.esm27.algorithm.iot.devices.algorithmservice.request.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.stronglink.esm27.algorithm.core.message.IMessageHandle;
import cn.stronglink.esm27.algorithm.core.util.ContextUtils;
import cn.stronglink.esm27.algorithm.iot.devices.algorithmservice.entity.GasAlgorithmManager;
import cn.stronglink.esm27.algorithm.iot.devices.algorithmservice.entity.GasDispersionParamsEntity;
import cn.stronglink.esm27.algorithm.iot.devices.algorithmservice.message.MQMessageOfESM27;
import cn.stronglink.esm27.algorithm.iot.devices.algorithmservice.task.AutoPushGasAlgorithmDatasTask;
import cn.stronglink.esm27.algorithm.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

public class StartGasDispersionAlgorithmServiceHandle implements IMessageHandle<MQMessageOfESM27, Object> {
	protected static Logger logger = LogManager.getLogger(StartGasDispersionAlgorithmServiceHandle.class.getName());
	protected TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	protected final static String ACTION_CODE="StartGasDispersionAlgorithmService";
	protected final static String SEND_ACTION_CODE="StartGasDispersionAlgorithmServiceReturn";
	protected AutoPushGasAlgorithmDatasTask autoPushGasAlgorithmDatasTask = (AutoPushGasAlgorithmDatasTask)ContextUtils.getBean("autoPushGasAlgorithmDatasTask");
	protected final static String SEND_TOPIC_NAME = "ESM27AlgorithmToService";
	@Override
	public boolean isHandle(MQMessageOfESM27 t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfESM27 t) {
		try {
		GasDispersionParamsEntity gasParams = ((JSONObject)t.getAwsPostdata()).toJavaObject(GasDispersionParamsEntity.class);
		GasAlgorithmManager.setGasDispersionParams(gasParams); // 将数据保存的公共变量中
		
		// 开启任务
		String strSpanTime = this.time2Cron((int)gasParams.getPushSpanSecond());
		autoPushGasAlgorithmDatasTask.setCron(strSpanTime); 
		
		logger.info("开启推送气体任务成功");
		
		sendReturnMessage(t.getTimestamp(),true,null); 
		}catch(Exception e) {
			sendReturnMessage(t.getTimestamp(),false,e.getMessage()); 
		}
		return null;
	}

	private void sendReturnMessage(long time,boolean isSuccess,String msg) {
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(SEND_ACTION_CODE);
		message.setTimestamp(time);
		message.setAwsPostdata(msg);
		message.setSuccess(isSuccess);

		String json = JSON.toJSONString(message);
		topicSender.send(SEND_TOPIC_NAME, json);
	}
	
	/**
	 * 时间转定时规则字符串
	 * @param time 需要定时执行的秒数
	 * @return
	 */
	private String time2Cron(int time) {
		int minute = time/60;
		int seconds = time % 60;
		String cron = "0/" +seconds + " 0/"+minute+ " * * * ?";
		cron = cron.replace("0/0", "*");
		return cron;
	}
}